package com.uziot.bucket.common.concurrent;

import com.uziot.bucket.common.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shidt
 * @version V1.0
 * @className SynchronizedLock
 * @date 2020-09-15 22:38:52
 * @description 这里简要介绍可重入锁
 * <br/>
 * <p>
 * 可重入锁指的是：
 * 当一个线程去尝试获取一个自己已经获得的锁的时候，会立即获取成功，并且计数器会+1
 * 当释放锁的时候，计数器会减少1，当计数值为0的时候，会释放锁。
 */
@Slf4j
public class SynchronizedLock {

    public static void main(String[] args) {
        new SynchronizedLock().test();
    }


    public void test1() {
        ReentrantLock reentrantLock = new ReentrantLock();
        ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
        reentrantLock.lock();
        try {
            stringThreadLocal.set("adsfjalksdfhalkdshfkjdsfasdf");
            System.out.println("asdfasdfasdf");
        } catch (Exception e) {
            log.error("系统发生异常，具体信息为：{}", ThrowableUtil.getStackTrace(e));
        } finally {
            reentrantLock.unlock();
            stringThreadLocal.remove();
        }


    }


    public void test() {
        synchronized (this) {
            System.out.println("执行第一层方法");
            while (true) {
                synchronized (this) {
                    System.out.println("执行内部方法");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }


        }


    }


}
